package TestSystemClient;

import javax.swing.*;

import java.awt.*;

import javax.swing.border.*;
import TestSystemIO.*;
import TestSystemUtil.*;

import java.awt.event.*;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;

@SuppressWarnings("serial")
public class ClientLogin extends JFrame {
	
	public Socket connection;
	public final Object writeLockObj = new Object();
	public final Object readLockObj = new Object();
	public InputThread inputThread;
	public OutputThread outputThread;
	
	public ArrayList<String> onlineUsers = new ArrayList<String>();
	public ArrayList<String> playerInfo = new ArrayList<String>();
	public Protocol protocol = new Protocol();
	public ClientUtil util = new ClientUtil();
	public Image image;
	
	public JPanel backgroundPanel, login;
	public JLabel nameLabel, label, idLabel, pwdLabel, versionLabel; 
	public JButton loginButton, regButton;
	public JTextField usernameTextField;
	public JPasswordField pwdTextField;
	public JPanel panel;
	public JPanel panel_1;
	public JPanel panel_2;
	public JPanel panel_3;
	public JLabel lblRegister;
	public JLabel lblUsername;
	public JTextField idTextField;
	public JLabel lblPassword;
	public JPasswordField passwordField;
	public JLabel lblClass;
	public JTextField fullnameTextField;
	public JLabel lblEmail;
	public JLabel lblPhone;
	public JTextField emailTextField;
	public JTextField phoneTextField;
	public JButton registerButton;
	public JButton backButton;
	public JComboBox<String> classComboBox;
	public JLabel lblFullname;
	
	
	//======== CLIENT LOGIN FRAME CONSTRUCTOR =======//
	public ClientLogin(Socket conn) {
		//=== COPY SOCKET, TẠO INPUT + OUTPUT THREAD, PROTOCOL ==//
		connection = conn;
		inputThread = util.makeInputThread(connection, readLockObj, protocol, this);
		outputThread = util.makeOutputThread(connection, writeLockObj);
		util.startSession(inputThread, outputThread);
		protocol.setState(Protocol.LOGIN);
		//=======================================================//
		
		//============== CREATE FRAME SINGLE PLAYER =============//
		createClientLoginFrame();
		//=======================================================//

		//================= CLICK LOGIN BUTTON ==================//
		loginButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if(usernameTextField.getText().isEmpty() || (pwdTextField.getPassword().length == 0)) {
					JOptionPane.showMessageDialog(null, "Username or Password field is empty", "Login Warning", JOptionPane.WARNING_MESSAGE);
				} else {
					Client.messageToServer = String.format(protocol.getMessageForm(), 
								usernameTextField.getText(), 
								new String(pwdTextField.getPassword())) + "\n";
					synchronized(writeLockObj) {
						writeLockObj.notify();
					}
					synchronized(readLockObj) {
						try {
							readLockObj.wait();
						} catch (InterruptedException ex) { }
					}
					switch(playerInfo.get(0)) {
						case "SUCCESS":
							Client.messageToServer = "INTERRUPT" + "\n";
							synchronized(writeLockObj) {
								writeLockObj.notify();
							}
							util.finishSession(inputThread, outputThread);
							ClientLogin.this.dispose();
							ClientSinglePlayer clientSinglePlayer = new ClientSinglePlayer(connection);
							playerInfo.add(usernameTextField.getText());
							clientSinglePlayer.setVisible(true);
							clientSinglePlayer.setPlayerInfo(playerInfo);
							clientSinglePlayer.setOnlineUsers(onlineUsers);
							break;
						case "ERR":
							JOptionPane.showMessageDialog(null, playerInfo.get(1), "ERROR", JOptionPane.WARNING_MESSAGE);
							usernameTextField.setText(null);
							pwdTextField.setText(null);
							break;
					}
				}
			}
		});
		//=======================================================//
		
		//================ CLICK REGISTER BUTTON  ===============//
		regButton.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				CardLayout card = (CardLayout) panel.getLayout();
				card.show(panel, "card2");
			}
		});
		//=======================================================//
		
		//================== CLICK BACK BUTTON ==================//
		backButton.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				CardLayout card = (CardLayout) panel.getLayout();
				card.show(panel, "card1");
			}
		});
		//=======================================================//
		//================ CLICK REGISTER BUTTON ================//
		registerButton.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if(idTextField.getText().isEmpty() || passwordField.getPassword().length == 0 || fullnameTextField.getText().isEmpty()
						|| classComboBox.getSelectedItem().toString().equals(" ")) {
					JOptionPane.showMessageDialog(null, "Empty Field", "Error", JOptionPane.WARNING_MESSAGE);
				} else {
					protocol.setState(Protocol.REGISTER);
					Client.messageToServer = String.format(protocol.getMessageForm(), 
							idTextField.getText(), new String(passwordField.getPassword()),
							fullnameTextField.getText(), classComboBox.getSelectedItem().toString(), 
							(emailTextField.getText().isEmpty()) ? " " : emailTextField.getText(),
							(phoneTextField.getText().isEmpty()) ? " " : phoneTextField.getText()) + "\n";
					protocol.setState(Protocol.LOGIN);
					synchronized(writeLockObj) {
						writeLockObj.notify();
					}
					synchronized(readLockObj) {
						try {
							readLockObj.wait();
						} catch (InterruptedException e1) { }
					}
					JOptionPane.showMessageDialog(null, inputThread.result.get(1), "Success", JOptionPane.INFORMATION_MESSAGE);
					clearRegisterForm();
				}
			}
		});
		//=======================================================//
		//================== CLOSE LOGIN FRAME ==================//
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				try {
					connection.close();
					if(inputThread.isAlive() || outputThread.isAlive()) {
						util.finishSession(inputThread, outputThread);
					}
				} catch (IOException e1) { }
			}
		});
		//=======================================================//
	}
	//=======================================================//
	
	//================= RESET REGISTER FORM =================//
	public void clearRegisterForm() {
		idTextField.setText("");
		passwordField.setText("");
		fullnameTextField.setText("");
		classComboBox.setSelectedIndex(0);
		emailTextField.setText("");
		phoneTextField.setText("");
	}
	//=======================================================//
	
	//=============== TẠO FRAME CLIENT LOGIN ================//
	public void createClientLoginFrame() {
		nameLabel = new JLabel("Multiple Choice Questions Test Client");
		label = new JLabel("");
		versionLabel = new JLabel("Multiple Choice Question Test Client - v1.0 beta");
		
		setResizable(false);
		setSize(new Dimension(800, 600));
		setLocationRelativeTo(null);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setTitle("Multiple Choice Questions Test Client");
		getContentPane().setLayout(null);
		
		backgroundPanel = new JPanel() {
			public void paintComponent(Graphics g) {
				image = Toolkit.getDefaultToolkit().getImage(ClientLogin.class.getResource("/resources/background.jpg"));
				g.drawImage(image, 0, 0, image.getWidth(null), image.getHeight(null), this);
			}
		};
		backgroundPanel.setForeground(new Color(0, 0, 0));
		backgroundPanel.setBounds(0, 0, 800, 600);
		getContentPane().add(backgroundPanel);
		backgroundPanel.setLayout(null);
		backgroundPanel.add(nameLabel);
		backgroundPanel.add(label);
		
		panel = new JPanel();
		panel.setOpaque(false);
		panel.setBounds(140, 170, 491, 351);
		backgroundPanel.add(panel);
		panel.setLayout(new CardLayout(0, 0));
		
		panel_1 = new JPanel();
		panel_1.setOpaque(false);
		panel.add(panel_1, "card1");
		panel_1.setLayout(null);
		login = new JPanel();
		login.setBounds(107, 49, 274, 149);
		panel_1.add(login);
		idLabel = new JLabel("Username :");
		pwdLabel = new JLabel("Password :");
		regButton = new JButton("Register");
		loginButton = new JButton("Login");
		usernameTextField = new JTextField();
		pwdTextField = new JPasswordField();
		
		login.setFont(new Font("Segoe Print", Font.PLAIN, 12));
		login.setOpaque(false);
		login.setBorder(new TitledBorder(null, "Login", TitledBorder.LEADING, TitledBorder.ABOVE_TOP, new Font("Segoe Print", Font.PLAIN, 12), null));
		login.setLayout(null);
		login.add(idLabel);
		login.add(usernameTextField);
		login.add(pwdLabel);
		login.add(loginButton);
		login.add(regButton);
		login.add(pwdTextField);
		
		usernameTextField.setBounds(119, 28, 132, 28);
		usernameTextField.setColumns(10);
		idLabel.setFont(new Font("Segoe Print", Font.PLAIN, 12));
		idLabel.setBounds(20, 35, 77, 14);
		pwdLabel.setFont(new Font("Segoe Print", Font.PLAIN, 12));
		pwdLabel.setBounds(20, 79, 77, 14);
		loginButton.setFont(new Font("Segoe Print", Font.PLAIN, 12));
		loginButton.setFocusCycleRoot(true);
		loginButton.setRequestFocusEnabled(false);
		loginButton.setFocusPainted(false);
		loginButton.setBounds(30, 112, 89, 23);
		regButton.setFont(new Font("Segoe Print", Font.PLAIN, 12));
		regButton.setRequestFocusEnabled(false);
		regButton.setBounds(144, 112, 89, 23);
		pwdTextField.setBounds(119, 72, 132, 28);
		
		panel_2 = new JPanel();
		panel_2.setOpaque(false);
		panel.add(panel_2, "card2");
		panel_2.setLayout(null);
		
		panel_3 = new JPanel() {
			public void paintComponent(Graphics g) {
			}
		};
		panel_3.setOpaque(false);
		panel_3.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
		panel_3.setLayout(null);
		panel_3.setBounds(106, 28, 293, 323);
		panel_2.add(panel_3);
		
		lblRegister = new JLabel("REGISTER");
		lblRegister.setHorizontalTextPosition(SwingConstants.CENTER);
		lblRegister.setHorizontalAlignment(SwingConstants.CENTER);
		lblRegister.setFont(new Font("Segoe Print", Font.PLAIN, 22));
		lblRegister.setBounds(23, 6, 238, 43);
		panel_3.add(lblRegister);
		
		lblUsername = new JLabel("Username :");
		lblUsername.setBounds(26, 50, 65, 25);
		panel_3.add(lblUsername);
		
		idTextField = new JTextField();
		idTextField.setColumns(10);
		idTextField.setBounds(134, 50, 127, 25);
		panel_3.add(idTextField);
		
		lblPassword = new JLabel("Password :");
		lblPassword.setBounds(26, 89, 62, 25);
		panel_3.add(lblPassword);
		
		passwordField = new JPasswordField();
		passwordField.setBounds(134, 88, 127, 25);
		panel_3.add(passwordField);
		
		lblClass = new JLabel("Class :");
		lblClass.setBounds(25, 169, 39, 25);
		panel_3.add(lblClass);
		
		fullnameTextField = new JTextField();
		fullnameTextField.setColumns(10);
		fullnameTextField.setBounds(134, 132, 127, 25);
		panel_3.add(fullnameTextField);
		
		lblEmail = new JLabel("Email :");
		lblEmail.setBounds(23, 206, 38, 25);
		panel_3.add(lblEmail);
		
		lblPhone = new JLabel("Phone :");
		lblPhone.setBounds(23, 243, 42, 25);
		panel_3.add(lblPhone);
		
		emailTextField = new JTextField();
		emailTextField.setColumns(10);
		emailTextField.setBounds(134, 206, 127, 25);
		panel_3.add(emailTextField);
		
		phoneTextField = new JTextField();
		phoneTextField.setColumns(10);
		phoneTextField.setBounds(134, 243, 127, 25);
		panel_3.add(phoneTextField);
		
		registerButton = new JButton("Register");
		registerButton.setRequestFocusEnabled(false);
		registerButton.setFocusPainted(false);
		registerButton.setBounds(33, 280, 89, 28);
		panel_3.add(registerButton);
		
		backButton = new JButton("Back");
		backButton.setRequestFocusEnabled(false);
		backButton.setFocusPainted(false);
		backButton.setFocusCycleRoot(true);
		backButton.setBorderPainted(false);
		backButton.setBounds(163, 280, 98, 28);
		panel_3.add(backButton);
		
		classComboBox = new JComboBox<String>();
		classComboBox.setModel(new DefaultComboBoxModel(new String[] {"VNK58", "VNK57", "VNK56", "VNK55", "VNK54", "VNK53", "VNK52"}));
		classComboBox.setRequestFocusEnabled(false);
		classComboBox.setFocusCycleRoot(true);
		classComboBox.setBounds(134, 169, 127, 25);
		panel_3.add(classComboBox);
		
		lblFullname = new JLabel("Fullname :");
		lblFullname.setBounds(25, 138, 66, 14);
		panel_3.add(lblFullname);
		backgroundPanel.add(versionLabel);
		
		nameLabel.setForeground(new Color(0, 0, 0));
		nameLabel.setBounds(0, 78, 794, 106);	
		nameLabel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
		nameLabel.setHorizontalTextPosition(SwingConstants.CENTER);
		nameLabel.setHorizontalAlignment(SwingConstants.CENTER);
		nameLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
		nameLabel.setFont(new Font("Segoe Print", Font.BOLD, 26));
		label.setBounds(0, 39, 770, 107);
		versionLabel.setBounds(486, 533, 284, 36);
		versionLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
	}
}
